package com.ego.user.controller;

import com.ego.user.pojo.User;
import com.ego.user.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author Ares
 * @date 2020-12-7
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> check(@PathVariable String data,@PathVariable Integer type){
        Boolean isTrue = userService.check(data,type);
        if(isTrue == null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.ok(isTrue);
    }

    @PostMapping("/code")
    public ResponseEntity<Void> sendSms(@RequestParam("phone")String phone){
        userService.sendSms(phone);
        return ResponseEntity.ok().build();
    }

    /**
     * 注册
     * @param user
     * @param code
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult bs, @RequestParam("code") String code) {
        //判断是否有错误
        if(bs.hasErrors())
        {
            return ResponseEntity.badRequest().build();
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("query")
    public User queryUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password){
        return userService.queryUser(username,password);
    }

    @PutMapping("/updatePw/{oldPassword}/{password}")
    public ResponseEntity<String> updatePassword(@PathVariable String oldPassword,@PathVariable String password){
        String mes = userService.updatePassword(oldPassword,password);
        return ResponseEntity.ok(mes);
    }

    @GetMapping("/phone")
    public ResponseEntity<String> getPhone(){
        String phone = userService.findPhone();
        return ResponseEntity.ok(phone);
    }

    @PostMapping("/confirm")
    public ResponseEntity<Boolean> isOKCode(@RequestParam("code") String code,@RequestParam("phone") String phone){
        Boolean bool = userService.confirm(code,phone);
        return ResponseEntity.ok(bool);
    }

    @PutMapping("updatePhone")
    public ResponseEntity<Boolean> updatePhone(@RequestParam("code") String code,@RequestParam("phone") String phone){
        Boolean bool = userService.updatePhone(code,phone);
        return ResponseEntity.ok(bool);
    }



}
